package thread.threaddemo;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @Author: wenjingyuan
 * @Date: 2022/11/11/19:30
 * @Description:编写代码，实现多线程数组求和
 */
public class ThreadDemo15 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long stime=System.currentTimeMillis();
        int[] arrs=new int[10000000];
        //对数组内的值进行初始化
        Random random=new Random();
        for (int i = 0; i < arrs.length; i++) {
            arrs[i]=(random.nextInt(100)+1);
        }

        //创建线程1来计算偶数
        FutureTask<Integer> task=new FutureTask<Integer>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int temp=0;
                for (int i = 0; i <arrs.length ; i=i+2) {
                 temp+=arrs[i];
                }
                System.out.println("偶数累加的和为："+temp);
                return temp;
            }
        });
        Thread thread=new Thread(task);
        thread.start();


        //创建线程2来计算奇数
        FutureTask<Integer> task1=new FutureTask<Integer>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int temp=0;
                for (int i = 1; i <arrs.length ; i=i+2) {
                    temp+=arrs[i];
                }
                System.out.println("奇数累加的和为："+temp);
                return temp;
            }
        });
        Thread thread1=new Thread(task1);
        thread1.start();
        //如果我们创建的是两个普通的线程，则必须要加join
//        thread.join();
//        thread1.join();
        int sum=task.get()+task1.get();
        System.out.println("累加的和为："+sum);
        long  etime=System.currentTimeMillis();
        System.out.println("程序执行时间为："+(etime-stime));
    }
}
